#include "maincontroller.h"
#include "sensor1worker.h"
#include "sensor3worker.h"
#include "motorworker.h"
#include "sensor2worker.h" // 需要添加这个头文件
#include <QThread>
#include <QTimer>
#include <QDateTime>
#include <MCDLL_NET.h>

MainController::MainController(QObject *parent)
    : QObject(parent),
    m_encoderTimer(new QTimer(this)),
    m_sensor1Thread(nullptr),
    m_sensor1Worker(nullptr),
    m_sensor2Thread(nullptr),
    m_sensor2Worker(nullptr),
    m_sensor3Thread(nullptr),
    m_sensor3Worker(nullptr),
    m_sensor4Thread(nullptr),
    m_sensor4Worker(nullptr),
    m_motorButtonThread(nullptr),
    m_motorWorker(nullptr),
    m_stopButtonThread(nullptr),
    m_stopWorker(nullptr),
    m_emergencyButtonThread(nullptr),
    m_emergencyWorker(nullptr)
{
    connect(m_encoderTimer, &QTimer::timeout, this, &MainController::updateEncoderCount);
    m_encoderTimer->start(10); // 10ms更新间隔
}

MainController::~MainController()
{
    stopAllSensors();
    MCF_Close_Net();
    delete m_encoderTimer;
}

int MainController::initialize()
{
    // 初始化控制卡
    ushort Station_Number = 0;
    ushort Station_Type = 2;
    short rtn = MCF_Open_Net(1, &Station_Number, &Station_Type);
    if (rtn != 0) {
        emit logMessage("[" + QDateTime::currentDateTime().toString() + "] Card opening failed! Check the hardware connection.");
    } else {
        emit logMessage("[" + QDateTime::currentDateTime().toString() + "] The control card initialization was successful.");
    }

    // 开启高速下降沿缓存
    MCF_Open_Input_Lock_Bit_Net(0, 0);

    // 初始化所有DO为关闭状态
    closeAllDO();
    return rtn;
}

void MainController::stopAllSensors()
{
    QMutexLocker locker(&m_mutex);

    // 停止所有工作对象
    if (m_sensor1Worker) m_sensor1Worker->stop();
    if (m_sensor2Worker) m_sensor2Worker->stop();
    if (m_sensor3Worker) m_sensor3Worker->stop();
    if (m_sensor4Worker) m_sensor4Worker->stop();
    if (m_motorWorker) m_motorWorker->stop();
    if (m_stopWorker) m_stopWorker->stop();
    if (m_emergencyWorker) m_emergencyWorker->stop();

    // 停止并删除线程
    if (m_sensor1Thread) {
        m_sensor1Thread->quit();
        m_sensor1Thread->wait();
        delete m_sensor1Thread;
        m_sensor1Thread = nullptr;
    }
    if (m_sensor2Thread) {
        m_sensor2Thread->quit();
        m_sensor2Thread->wait();
        delete m_sensor2Thread;
        m_sensor2Thread = nullptr;
    }
    if (m_sensor3Thread) {
        m_sensor3Thread->quit();
        m_sensor3Thread->wait();
        delete m_sensor3Thread;
        m_sensor3Thread = nullptr;
    }
    if (m_sensor4Thread) {
        m_sensor4Thread->quit();
        m_sensor4Thread->wait();
        delete m_sensor4Thread;
        m_sensor4Thread = nullptr;
    }
    if (m_motorButtonThread) {
        m_motorButtonThread->quit();
        m_motorButtonThread->wait();
        delete m_motorButtonThread;
        m_motorButtonThread = nullptr;
    }
    if (m_stopButtonThread) {
        m_stopButtonThread->quit();
        m_stopButtonThread->wait();
        delete m_stopButtonThread;
        m_stopButtonThread = nullptr;
    }
    if (m_emergencyButtonThread) {
        m_emergencyButtonThread->quit();
        m_emergencyButtonThread->wait();
        delete m_emergencyButtonThread;
        m_emergencyButtonThread = nullptr;
    }

    // 重置工作对象指针
    m_sensor1Worker = nullptr;
    m_sensor2Worker = nullptr;
    m_sensor3Worker = nullptr;
    m_sensor4Worker = nullptr;
    m_motorWorker = nullptr;
    m_stopWorker = nullptr;
    m_emergencyWorker = nullptr;

    // 重置运行标志
    m_sensor1Running = false;
    m_sensor2Running = false;
    m_sensor3Running = false;
    m_sensor4Running = false;
    m_motorRunning = false;
    m_stopRunning = false;
    m_emergencyRunning = false;
}

void MainController::startSensor1(ushort di, ushort d0)
{
    QMutexLocker locker(&m_mutex);

    if (m_sensor1Running) {
        m_sensor1Worker->stop();
        m_sensor1Thread->quit();
        m_sensor1Thread->wait();
    }

    m_sensor1Thread = new QThread();
    m_sensor1Worker = new Sensor1Worker(di, d0);

    m_sensor1Worker->moveToThread(m_sensor1Thread);

    connect(m_sensor1Thread, &QThread::started, m_sensor1Worker, &Sensor1Worker::process);
    connect(m_sensor1Worker, &Sensor1Worker::finished, m_sensor1Worker, &QObject::deleteLater);
    connect(m_sensor1Worker, &Sensor1Worker::finished, m_sensor1Thread, &QThread::quit);
    connect(m_sensor1Worker, &Sensor1Worker::log, this, &MainController::logMessage);

    m_sensor1Running = true;
    m_sensor1Thread->start();
}

void MainController::startSensor2(ushort di, ushort d0)
{
    QMutexLocker locker(&m_mutex);

    if (m_sensor2Running) {
        m_sensor2Worker->stop();
        m_sensor2Thread->quit();
        m_sensor2Thread->wait();
    }

    m_sensor2Thread = new QThread();
    m_sensor2Worker = new Sensor2Worker(di, d0);

    m_sensor2Worker->moveToThread(m_sensor2Thread);

    connect(m_sensor2Thread, &QThread::started, m_sensor2Worker, &Sensor2Worker::process);
    connect(m_sensor2Worker, &Sensor2Worker::finished, m_sensor2Worker, &QObject::deleteLater);
    connect(m_sensor2Worker, &Sensor2Worker::finished, m_sensor2Thread, &QThread::quit);
    connect(m_sensor2Worker, &Sensor2Worker::log, this, &MainController::logMessage);

    m_sensor2Running = true;
    m_sensor2Thread->start();
}

void MainController::startSensor3(ushort di, ushort d0, int startCount, int endCount)
{
    QMutexLocker locker(&m_mutex);

    if (m_sensor3Running) {
        m_sensor3Worker->stop();
        m_sensor3Thread->quit();
        m_sensor3Thread->wait();
    }

    m_sensor3Thread = new QThread();
    m_sensor3Worker = new Sensor3Worker(di, d0, startCount, endCount);

    m_sensor3Worker->moveToThread(m_sensor3Thread);

    connect(m_sensor3Thread, &QThread::started, m_sensor3Worker, &Sensor3Worker::process);
    connect(m_sensor3Worker, &Sensor3Worker::finished, m_sensor3Worker, &QObject::deleteLater);
    connect(m_sensor3Worker, &Sensor3Worker::finished, m_sensor3Thread, &QThread::quit);
    connect(m_sensor3Worker, &Sensor3Worker::log, this, &MainController::logMessage);

    m_sensor3Running = true;
    m_sensor3Thread->start();
}

void MainController::startSensor4(ushort di, ushort d0, int startCount, int endCount)
{
    QMutexLocker locker(&m_mutex);

    if (m_sensor4Running) {
        m_sensor4Worker->stop();
        m_sensor4Thread->quit();
        m_sensor4Thread->wait();
    }

    m_sensor4Thread = new QThread();
    m_sensor4Worker = new Sensor3Worker(di, d0, startCount, endCount);

    m_sensor4Worker->moveToThread(m_sensor4Thread);

    connect(m_sensor4Thread, &QThread::started, m_sensor4Worker, &Sensor3Worker::process);
    connect(m_sensor4Worker, &Sensor3Worker::finished, m_sensor4Worker, &QObject::deleteLater);
    connect(m_sensor4Worker, &Sensor3Worker::finished, m_sensor4Thread, &QThread::quit);
    connect(m_sensor4Worker, &Sensor3Worker::log, this, &MainController::logMessage);

    m_sensor4Running = true;
    m_sensor4Thread->start();
}

void MainController::startMotorButton(ushort di, ushort d0)
{
    MCF_Set_Output_Bit_Net(0, 0, 0);
    // QMutexLocker locker(&m_mutex);

    // if (m_motorRunning) {
    //     m_motorWorker->stop();
    //     m_motorButtonThread->quit();
    //     m_motorButtonThread->wait();
    // }

    // m_motorButtonThread = new QThread();
    // m_motorWorker = new MotorWorker(di, d0, 0); // 0:启动模式

    // m_motorWorker->moveToThread(m_motorButtonThread);

    // connect(m_motorButtonThread, &QThread::started, m_motorWorker, &MotorWorker::process);
    // connect(m_motorWorker, &MotorWorker::finished, m_motorWorker, &QObject::deleteLater);
    // connect(m_motorWorker, &MotorWorker::finished, m_motorButtonThread, &QThread::quit);
    // connect(m_motorWorker, &MotorWorker::log, this, &MainController::logMessage);
    // connect(m_motorWorker, &MotorWorker::motorStateChanged, this, [this](bool running) {
    //     if (running) emit motorStarted();
    // });

    // m_motorRunning = true;
    // m_motorButtonThread->start();
}

void MainController::startStopButton(ushort di, ushort d0)
{
    MCF_Set_Output_Bit_Net(0, 1, 0);
    // QMutexLocker locker(&m_mutex);

    // if (m_stopRunning) {
    //     m_stopWorker->stop();
    //     m_stopButtonThread->quit();
    //     m_stopButtonThread->wait();
    // }

    // m_stopButtonThread = new QThread();
    // m_stopWorker = new MotorWorker(di, d0, 1); // 1:停止模式

    // m_stopWorker->moveToThread(m_stopButtonThread);

    // connect(m_stopButtonThread, &QThread::started, m_stopWorker, &MotorWorker::process);
    // connect(m_stopWorker, &MotorWorker::finished, m_stopWorker, &QObject::deleteLater);
    // connect(m_stopWorker, &MotorWorker::finished, m_stopButtonThread, &QThread::quit);
    // connect(m_stopWorker, &MotorWorker::log, this, &MainController::logMessage);
    // connect(m_stopWorker, &MotorWorker::motorStateChanged, this, [this](bool running) {
    //     if (!running) emit motorStopped();
    // });

    // m_stopRunning = true;
    // m_stopButtonThread->start();
}

void MainController::startEmergencyButton(ushort di, ushort d0)
{
    QMutexLocker locker(&m_mutex);

    if (m_emergencyRunning) {
        m_emergencyWorker->stop();
        m_emergencyButtonThread->quit();
        m_emergencyButtonThread->wait();
    }

    m_emergencyButtonThread = new QThread();
    m_emergencyWorker = new MotorWorker(di, d0, 2); // 2:急停模式

    m_emergencyWorker->moveToThread(m_emergencyButtonThread);

    connect(m_emergencyButtonThread, &QThread::started, m_emergencyWorker, &MotorWorker::process);
    connect(m_emergencyWorker, &MotorWorker::finished, m_emergencyWorker, &QObject::deleteLater);
    connect(m_emergencyWorker, &MotorWorker::finished, m_emergencyButtonThread, &QThread::quit);
    connect(m_emergencyWorker, &MotorWorker::log, this, &MainController::logMessage);
    connect(m_emergencyWorker, &MotorWorker::motorStateChanged, this, [this](bool running) {
        if (!running) emit motorStopped();
    });

    m_emergencyRunning = true;
    m_emergencyButtonThread->start();
}

void MainController::updateEncoderCount()
{
    long encoder_count = 0;
    long position = 0;
    short rtn = MCF_Get_Encoder_Net(0, &encoder_count, 0);
    MCF_Get_Position_Net(0, &position, 0);

    if (rtn == 0) {
        emit encoderCountUpdated(static_cast<int>(encoder_count), static_cast<int>(position));
    }
}

void MainController::emergencyStop()
{
    closeAllDO();
    MCF_Axis_Stop_Net(0, 0, 0);
    emit logMessage("[" + QDateTime::currentDateTime().toString() + "] Emergency stop triggered");
    emit motorStopped();
}

void MainController::closeAllDO()
{
    MCF_Set_Output_Net(0xFFFF, 0);
    emit logMessage("[" + QDateTime::currentDateTime().toString() + "] All outputs have been turned off.");
}
